<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>简单轮播</title>
    <style>
      #banner {
        width: 50%;
        height: 300px;
        margin: 20px auto;
      }
      #banner a {
        text-decoration: none;
      }
      #banner img {
        width: 100%;
        height: 100%;
        display: block;
        border: 0;
      }
    </style>
  </head>
  <body>
    <div id="banner">
      <a href="1.html"><img src="./images/1.jpg" alt="banner" /></a>
    </div>
  </body>
  <script>
    // mock(模拟)数据
    var imgs = [
      { src: "1.jpg", url: "1.html" },
      { src: "2.jpg", url: "2.html" },
      { src: "3.jpg", url: "3.html" },
      { src: "4.jpg", url: "4.html" },
    ];
    var idx = 0; //设置初始图，0表示第一张图
    var timer = null; //初始化计时器
    // 获取DOM
    var banner = document.getElementById("banner");

    //循环遍历获取到的数据
    function carousel(imgs) {
      // 下标越界处理
      if (idx >= imgs.length - 1) {
        idx = 0;
      } else {
        idx++;
      }
      console.log(idx);
      // 动态改变组图和a标签跳转地址
      banner.children[0].href = imgs[idx].url;
      banner.getElementsByTagName("img")[0].src = "images/" + imgs[idx].src;
    }

    // 设置计时器
    timer = setInterval("carousel(imgs)", 2000); //重复调用函数，相当于执行了循环
    // setInterval 调用函数时必须加引号

    // 鼠标悬停到组图时将停止轮播
    banner.onmouseover = function () {
      // 清除轮播实现，停止轮播
      clearInterval(timer);
    };
    // 鼠标移走时将继续轮播
    banner.onmouseout = function () {
      timer = setInterval("carousel(imgs)", 2000);
    };
  </script>
</html>
